import {useState, useEffect} from 'react';
import {connect} from "react-redux";
import moment from 'moment';
import {View} from '@tarojs/components'
import Taro, {useDidShow} from '@tarojs/taro'
import { Loading, Overlay, ConfigProvider, Picker, Drag, Dialog } from '@nutui/nutui-react-taro';
import { AtButton} from "taro-ui";
import { AngleDoubleRight, Check } from "@nutui/icons-react-taro";
import ChargingAnimation from '../../../components/chargingAnimation';
import {getRandomFloorNum} from '../../../utils'
import './index.less'

let Timer;
let TIMER;
let timer;
function Index(props) {
    const randomSeconds = getRandomFloorNum(1, 60);
    const {dispatch, chargingOrderInfo = {}, balance, loading} = props;
    Taro.onNetworkStatusChange((RES) => {
        console.log('充电中页面网络变化', RES);
        if (RES.isConnected) {
            //有网了以后，清空没网标识，进行页面刷新数据请求等...
            console.log('有网了,网是', RES.networkType);
            dispatch({
                // type: 'stations/getChargingOrderInfo'
                type: 'stations/initCharging',
            });
            dispatch({
                type: 'wallet/getBalance'
            })
        } else {
            console.log('没网了');
        }

    })
    const {
        createTime = '',
        exportVoltage = '0.00',  //输出电压
        exportElectricity = '0.00',  //输出电流
        chargingPower = '',  //充电实时功率
        duration = 0, // 充电时长
        soc = 0,
        totalBattery = '0.00', // 电量
        totalMoney = '0.00', // 金额
        pileCode = '', // 桩编码
        pileId = '', //桩id,
        gunNum = '',  //枪编码,
        orderNum = '', // 交易单号
        serialNum = '' // 流水号
    } = chargingOrderInfo;
    const timeStampForChargingBegin = Taro.getStorageSync('timeStampForChargingBegin');
    const timeStampChargingBegin = Taro.getStorageSync('timeStampChargingBegin');
    const nowTimeStamp = new Date().getTime();
    const diffSecond = timeStampForChargingBegin ? 60 - parseInt((nowTimeStamp - timeStampForChargingBegin) / 1000) : 0;
    const startTime = createTime || timeStampChargingBegin || '';
    const [TIME, setTIME] = useState(diffSecond);
    // console.log('正在充电前端页面获取的数据', props);
    const [time, setTime] = useState(duration * 60);
    const [socPickerVisible, setSocPickerVisible] = useState(false);
    const [startPoint, setStartPoint] = useState(0);
    const [shutDownModal, setShutDownModalVisible] = useState(false);
    const [toEnd, setToEnd] = useState(false);
    const socOptions = [[]]
    useDidShow(() => {
        console.log('useDidShow的请求时间', moment().format('YYYY-MM-DD HH:mm:ss'))
      setTime(duration * 60 + randomSeconds)
        dispatch({
            // type: 'stations/getChargingOrderInfo'
            type: 'stations/initCharging',
        });
      dispatch({
        type: 'wallet/getBalance'
      })
    });
    useEffect(() => {
        console.log('TIME', TIME);
        setTime(duration * 60 + randomSeconds)
        timer = setInterval(() => {
            setTime((T) => T + 1)
        }, 1000);
        setTimeout(() => {
            console.log('useEffect的setTimeout', moment().format('YYYY-MM-DD HH:mm:ss'))
            dispatch({
                // type: 'stations/getChargingOrderInfo'
                type: 'stations/initCharging',
            });
            Timer = setInterval(() => {
                console.log('useEffect的setInterval', moment().format('YYYY-MM-DD HH:mm:ss'))
                dispatch({
                    type: 'stations/initChargingPage',
                })
            }, 30000);
        }, TIME >= 3 ? 3000 : 0) //fix: 进入该页面没有满足3s就执行结束充电操作,导致返回到主页后,定时器在3s时仍会触发的问题.
        if (timeStampForChargingBegin && diffSecond && diffSecond > 0){
            TIMER = setInterval(() => {
                setTIME((T) => T - 1)
            }, 1000);
        } else {
            clearInterval(TIMER);
            Taro.removeStorage({key: 'timeStampForChargingBegin'})
        }
        return () => {
            console.log('正在充电的销毁期')
            clearInterval(timer)
            clearInterval(Timer)
        }
    }, [dispatch]);
    if (!timeStampForChargingBegin || !diffSecond || diffSecond <=0){
        clearInterval(TIMER);
        Taro.removeStorage({key: 'timeStampForChargingBegin'})
    }
    const chargingTime = moment.duration(time, 'seconds');
    let hours = chargingTime.hours()
    let minutes = chargingTime.minutes()
    let seconds = chargingTime.seconds()
    const WrapperStyle = {
        display: 'flex',
        height: '100%',
        alignItems: 'center',
        justifyContent: 'center'
    }

    function confirmSocPicker(opts, values) {
        console.log('options', opts);
        console.log('values', values);
    }

  return (
    <View className='chargingDetailWrap'>
      {
        loading ?
          <Overlay visible={loading}>
            <div className='wrapper' style={WrapperStyle}>
              <Loading direction='vertical'>加载中...</Loading>
            </div>
          </Overlay> :
          <View>
            <View className='cardContent'>
              <View className='cardContentSon'>
                <View className='target'>{exportElectricity}</View>
                <View>电流(A)</View>
              </View>
                <View className='cardContentSon'>
                    <View className='target'>{((parseFloat(exportElectricity) * parseFloat(exportVoltage)) / 1000 ).toFixed(2) || '-'}</View>
                    <View>功率(Kw)</View>
                </View>
              <View className='cardContentSon'>
                <View className='target'>{exportVoltage}</View>
                <View>电压(V)</View>
              </View>
            </View>
              <View className='time'>{moment({h:hours, m:minutes, s:seconds}).format('HH:mm:ss')}</View>
            <ChargingAnimation number={soc} />
            <View className='stationInfo'>
              <View className='cardContent'>
                <View className='cardContentSon'>
                  <View className='target'>{totalBattery}度</View>
                  <View>充电电量</View>
                </View>
                  <View className='cardContentSon'>
                      <View className='target'>{startTime ? moment(startTime).format('HH:mm:ss') : ''}</View>
                      <View>开始时间</View>
                  </View>
                <View className='cardContentSon'>
                  <View className='target'>{totalMoney}元</View>
                  <View>充电费用</View>
                </View>
              </View>
            </View>
            {/*<View className='chargeInfoCard'>*/}
            {/*  <View> 账户余额</View>*/}
            {/*  <View style={{fontWeight: 'bold', color: '#ff6659'}}> {balance.toFixed(2)}元</View>*/}
            {/*</View>*/}
            {/*<View className='chargeInfoCard'>*/}
            {/*  <View> 优惠卡券</View>*/}
            {/*  <View onClick={() => setSocPickerVisible(true)}>*/}
            {/*    {<Tag type='warning' round>有折扣卡券 <AtIcon prefixClass='icon' value='kaquan' size='14' color='#ffffff' /></Tag> || <Tag type='warning'>标签</Tag>}*/}
            {/*    <AtIcon value='chevron-right' size='18' color='#767E8E' />*/}
            {/*  </View>*/}
            {/*</View>*/}
            {/*<View className='chargeInfoCard'>*/}
            {/*  <View> 车牌号码</View>*/}
            {/*  <View style={{fontWeight: 'bold', color: '#1afa29'}}> 豫AD00001</View>*/}
            {/*</View>*/}
          </View>
      }
        {
            TIME > 0 && timeStampForChargingBegin ? <View className='pageFooter'>
                <AtButton disabled={diffSecond > 0} onClick={() => {
                    dispatch({
                        type: 'stations/finishCharge',
                        payload: {
                            pileId,
                            pileCode,
                            interfaceCode: gunNum,
                            tradeNo: orderNum,
                            serialNum: serialNum
                        }
                    })
                }}
                >  {`${TIME}s后才能结束充电`}</AtButton>
            </View> : <View className='scanFooter'>
                <div className='dragWrap'>
                    <Drag
                      onTouchStart={(e) => {
                            console.log('onTouchStart', e);
                            setStartPoint(e.changedTouches.length ? e.changedTouches[0]?.pageX : 0)
                        }}
                      onTouchEnd={(e) => {
                        try {
                          const screenWidth = Taro.getSystemInfoSync().windowWidth;
                          const trueWidth = ((screenWidth * 0.95) - 24 - 25) * 0.5;
                          const end = e.changedTouches.length ? e.changedTouches[0]?.pageX : 0;
                          if (end > startPoint && (end - startPoint) >= trueWidth && diffSecond <= 0){
                            console.log('我要结束了');
                            setToEnd(true);
                            setTimeout(() => {
                              setShutDownModalVisible(true);
                            }, 500)
                          }
                        } catch (e) {

                        }
                        }}
                        // onTouchMove={(e) => {
                        //   const screenWidth = Taro.getSystemInfoSync().windowWidth;
                        //   console.log('screenWidth', screenWidth);
                        //   console.log('onTouchMove', e);
                        // }}
                      attract
                      direction='x'
                      style={{left: '12px'}}
                      boundary={{left: 12, right: 12}}
                    >
                        <View className='shutDownBtn'>
                            {toEnd ? <Check style={{color: '#ff5458'}} /> : <AngleDoubleRight style={{color: '#ff5458'}} />}
                        </View>
                    </Drag>
                    {toEnd ? '验证通过' : '滑动结束充电'}
                </div>
            </View>
        }
      <ConfigProvider theme={{nutuiPickerOkColor: '#0091FF'}}>
        <Picker
          // title='请选择车辆安全控制'
          visible={socPickerVisible}
          options={socOptions}
          // threeDimensional={false}
          duration={1000}
          onConfirm={(list, values) => confirmSocPicker(list, values)}
          onClose={() => setSocPickerVisible(false)}
        />
      </ConfigProvider>
      <Dialog
        title='温馨提示'
        cancelText='取消'
        confirmText='确认'
        visible={shutDownModal}
        onConfirm={() => {
          console.log('gunNum', gunNum);
          console.log('orderNum', orderNum);
          dispatch({
              type: 'stations/finishCharge',
              payload: {
                  pileId,
                  pileCode,
                  interfaceCode: gunNum,
                  tradeNo: orderNum
              }
          })
        }}
        onCancel={() => {
            setShutDownModalVisible(false);
            Taro.redirectTo({url: '/moduleA/pages/charging/index'})
        }}
      >
          <View
            style={{
                display: 'flex',
                justifyContent: 'center',
                fontSize: '28rpx',
                fontWeight: 'bold',
                flexWrap: 'wrap',
                // color: '#FFA500'
            }}
          >
              <View>您确定要结束充电吗?</View>
          </View>
      </Dialog>
    </View>
  )
}

function mapStateToProps({
                             stations: {chargingOrderInfo = {}} = {},
                             wallet: {balance = {}} = {},
                             loading: {effects: {"stations/initDetail": loading = false} = {}} = {},
                         }) {
    return {
        chargingOrderInfo,
        balance,
        loading,
    };
}

export default connect(mapStateToProps)(Index);
